<template>
  <div class="addressBox">
    <div class="addAddressBox">
      <span class="addAddressBtn" @click="addAddressBtn">新增收货地址</span>
    </div>
    <div v-loading="addressLoading">
      <div class="addressList clearfix sub-main" v-if="addressData?.length">
        <div
          class="addressItem"
          v-for="(item) of addressData"
          :class="{active: item.ifDefault}"
          :key="item.receiveId"
        >
          <div class="listItemInfoBox">
            <div class="isDefault">
              <span>设为默认地址</span>
              <el-switch
                v-model="item.ifDefault"
                :active-value="1"
                :inactive-value="0"
                @change="changeDefultAd(item)"
                active-color="#C5AA7B"
                inactive-color="#c1c1c1"
              />
            </div>
            <div class="addressInfo">
              <div
                class="infoItem infoName"
                :title="item.receiveName"
              >{{ item.receiveName }}</div>
              <div class="infoItem">
                {{ item.receiveAdress }}-{{ item.address }}
              </div>
              <!-- <div class="infoItem"></div> -->
              <div class="infoItem infoPhone">
                {{ item.receivePhone }}
              </div>
              <div class="btns">
                <span class="btnItem" @click="showDelete(item)">
                  <i class="iconfont">&#xe62c;</i>
                </span>
                <span class="btnItem" @click="changeAddress(item)">
                  <i class="iconfont">&#xe605;</i>
                </span>
                <div v-show="item.ifDefault" class="iconfont defaultActive">&#xe612;</div>
              </div>
            </div>
          </div>
        </div>
        <div class="clearfix"></div>
        <el-pagination
          :hide-on-single-page="true"
          v-model:current-page="page.page"
          v-model:page-size="page.pageSize"
          background
          layout="prev, pager, next, jumper"
          :total="page.total"
          @current-change="getAddressList"
        />
      </div>
      <div class="nothing sub-main" v-else>
        <svg-icon style="width: 240px; height: 240px; margin-bottom: 20px;" name="user-dingwei-nodata" />
        <p class="fs20 font-color-999">你还没有收货地址～</p>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      v-model="visible.add"
      :close-on-click-modal="false"
      width="750px">
      <AddAddress
        :data="addressInfo"
        @hide-add-dialog="hideAddDialog"
        @cancel-add="closeAdd"
      />
    </el-dialog>
    <el-dialog
      title="是否删除此项"
      v-model="visible.delete"
      width="30%">
      <div class="deleteAddInfo">
        <p>收货人： {{ deleteCurrent.receiveName }}</p>
        <p>手机号码： {{ deleteCurrent.receivePhone }}</p>
        <p>收货地址： {{ deleteCurrent.receiveAdress }} {{ deleteCurrent.address }}</p>
      </div>
      <template #footer>
        <el-button
          type="primary"
          @click="deleteAdd"
        >确 定</el-button>
        <el-button @click="visible.delete = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineComponent, onBeforeMount, reactive, ref, shallowRef } from 'vue'
import AddAddress from '@/components/orderInfo/addAddress'
import SvgIcon from '@/components/svgIcon/index.vue';
import { TextToCode } from 'element-china-area-data'
import { useUser } from '@/store/user'
import {
  getAllAddressList,
  addAddress,
  updateAddress,
  deleteAddress
} from '@/api/user/address.js'
import { ElMessage } from 'element-plus';



defineComponent({
  name: 'SigningAddress'
})

const userStore = useUser()
const page = reactive({
  page: 1,
  pageSize: 4,
  total: 0
})
const addressLoading = shallowRef(false);
const addressData = ref([]);

const addressInfo = ref({
  receiveName: '',
  receivePhone: '',
  receiveAdress: '',
  address: '',
  label: '',
  ifDefault: 0, // 0 / 1 默认
})

function getAddressList () {
  addressLoading.value = true
  getAllAddressList({
    page: page.page,
    pageSize: page.pageSize
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      addressData.value = res.data && res.data.list
      page.total = parseInt(res.data.total)
    }
  }).catch(err => ElMessage.error(err.message))
    .finally(() => addressLoading.value = false)
}

const visible = reactive({
  delete: false,
  add: false,
})
const dialogTitle = shallowRef('新建收货地址');

const deleteCurrent= ref({});
function showDelete (item) {
  visible.delete = true;
  deleteCurrent.value = item
}

// 删除地址
function deleteAdd () {
  deleteAddress({ receiveId: deleteCurrent.value.receiveId }).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('删除成功')
      page.page = 0
      addressData.value = []
      getAddressList()
    }
  }).catch(err => ElMessage.error(err.message))
    .finally(() => visible.delete = false)
}
// 修改默认地址
function changeDefultAd (item) {
  if (addressLoading.value) { return }
  addressLoading.value = true
  updateAddress({
    receiveId: item.receiveId,
    ifDefault: item.ifDefault
  }).then(res => {
    if (res.data.code === '200') {
      ElMessage.success('默认地址设置成功')
      getAddressList()
    }
  }).catch(err => {
    ElMessage.error(err.message)
  }).finally(() => addressLoading.value = false)
}

// 修改地址信息
function changeAddress (item) {
  console.log(item)
  let addressData = item.receiveAdress.split('-')
  let areaData = []
  addressData[0] && areaData.push(TextToCode[addressData[0]].code)
  addressData[0] && areaData.push(TextToCode[addressData[0]][addressData[1]].code)
  addressData[0] && areaData.push(TextToCode[addressData[0]][addressData[1]][addressData[2]].code)
  addressInfo.value = item
  userStore.setAreaCode(areaData)
  dialogTitle.value = '修改收货地址'
  visible.add = true
}

function addAddressBtn () {
  addressInfo.value = {
    receiveName: '',
    receivePhone: '',
    receiveAdress: '',
    address: '',
    label: '',
    ifDefault: 0
  }
  userStore.setAreaCode([])
  dialogTitle.value = '新增收货地址'
  visible.add = true
}


function hideAddDialog () {
  visible.add = false
  let fn;
  fn = addressInfo.value.receiveId ? updateAddress : addAddress
  delete addressInfo.value.buyerUserId
  fn(addressInfo.value).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('操作成功')
      page.page = 1
      addressData.value = []
      userStore.setAreaCode([])
      getAddressList()
    }
  }).catch(err => ElMessage.error(err.message))
}

function closeAdd () {
  visible.add = false
}

onBeforeMount(() => {
  getAddressList()
})

</script>

<style lang="scss" scoped>
.addressBox {
  border: 1px solid #E5E5E5;
  min-height: 500px;
  .addAddressBox{
    height: 50px;
    background-color: #FAFAFA;
    .addAddressBtn {
      font-size: 16px;
      color: $mainGlod;
      line-height: 50px;
      // background: #FFFFFF;
      // border: 1px solid $mainGlod;
      border-radius: 4px;
      padding: 4px 20px;
      cursor: pointer;
    }
  }
  .addressList {
    margin-top: 20px;
    .addressItem {
      // width: 477px;
      border: 2px solid #DDDDDD;
      border-radius: 4px;
      box-sizing: border-box;
      margin: 20px;
      .listItemInfoBox {
        padding: 20px;
        .isDefault {
          display: flex;
          align-items: center;
          height: 35px;
          // justify-content: flex-end;
          span {
            color: #333333;
            font-size: 16px;
            margin-right: 5px;
          }
        }
        .addressInfo {
          display: flex;
          .infoItem {
            flex: 10;
            color: #333333;
            font-size: 16px;
            margin: 30px;
          }
          .infoName{
            flex: 5;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .infoPhone{
            flex: 5;
          }
          .infoItem:last-child {
            margin-bottom: 0;
          }
          .btns{
            width: 100px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            i{
              font: 20px !important;
            }
            .btnItem{
              cursor: pointer;
            }
          }
        }
      }
      .addressChange {
        border-top: #CCCCCC solid 1px;
        height: 45px;
        line-height: 45px;
        position: relative;
        i {
          margin-right: 5px;
        }
        .defaultActive {
          position: absolute;
          right: -1px;
          bottom: -3px;
          width: 46px;
          height: 46px;
          color: $mainGlod;
          font-size: 46px;
        }
        span {
          display: block;
          float: left;
          width: 50%;
          color: #666666;
          text-align: center;
          cursor: pointer;
        }
        span:nth-child(2) {
          border-left: 1px solid #CCCCCC;
          color: $mainGlod;
          box-sizing: border-box;
        }
      }
    }
    .active {
      border: 2px solid $mainGlod;
    }
  }
  :deep(.el-dialog){
    .el-dialog__header {
      text-align: center;
    }
    .dialog-footer {
      display: flex;
      justify-content: center;
      width: 100%;
      button {
        width: 200px;
        height: 50px;
      }
    }
  }
  .deleteAddInfo {
    width: 70%;
    margin: 0 auto;
    p {
      line-height: 30px;
    }
  }
  :deep(.el-pagination){
    text-align: right;
    margin: 20px;
  }
}
.sub-main{
  min-height: 400px;
}
.nothing{
  width: 100%;
  margin: 20px;
  text-align: center;
  min-height: 400px;
  p{
    margin-bottom: 20px;
  }
  .el-button{
    background-color: $mainGlod;
    color: #FFFFFF;
    font-weight: normal;
    border-radius: 0;
  }
}
.el-pagination {
  justify-content: flex-end;
}
</style>
